import React, { useEffect, useState } from "react";
import { Button } from "antd";

const App = () => {
  const [apiStatus, setApiStatus] = useState("未连接");
  const [canTranslate, setCanTranslate] = useState(false);
  const [canDownload, setCanDownload] = useState(false);

  useEffect(() => {
    // 检查API密钥状态
    chrome.storage.sync.get(["apiKey"], (result) => {
      if (result.apiKey) {
        setApiStatus("已连接");
      }
    });

    // 监听当前标签页状态，确定是否可以翻译和下载
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      if (tabs[0]?.url && tabs[0].url.startsWith("http")) {
        setCanTranslate(true);
      }
    });

    // 监听翻译状态，确定是否可以下载
    chrome.storage.local.get(["translatedContent"], (result) => {
      if (result.translatedContent) {
        setCanDownload(true);
      }
    });
  }, []);

  // 触发翻译功能
  const handleTranslate = () => {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      chrome.tabs.sendMessage(tabs[0].id, { action: "translate" });
    });
  };

  // 触发下载功能
  const handleDownload = (format) => {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      chrome.tabs.sendMessage(tabs[0].id, { action: "download", format });
    });
  };

  // 打开设置页面
  const openSettings = () => {
    chrome.runtime.openOptionsPage();
  };

  return (
    <div className="popup">
      <div className="popup-header">
        <div className="popup-logo"></div>
        <h3 className="popup-title">DeepSeek翻译</h3>
      </div>

      <Button
        type="primary"
        className="action-button"
        onClick={handleTranslate}
        disabled={!canTranslate || apiStatus === "未连接"}
      >
        翻译当前页面
      </Button>

      <Button
        className="action-button secondary-button"
        onClick={() => handleDownload("markdown")}
        disabled={!canDownload}
      >
        下载为Markdown
      </Button>

      <Button
        className="action-button secondary-button"
        onClick={() => handleDownload("pdf")}
        disabled={!canDownload}
      >
        下载为PDF
      </Button>

      <div className="status-bar">
        API状态: {apiStatus}
        <span className="settings-link" onClick={openSettings}>
          设置
        </span>
      </div>
    </div>
  );
};

export default App;
